package com.icesoft.core.web.suppose.token.filter;

import com.icesoft.core.common.helper.AnnotationUtil;
import com.icesoft.core.web.suppose.token.AuthTokenCheck;
import com.icesoft.core.web.suppose.token.IAuthToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * token参数解析器
 */
@Slf4j
public class AuthTokenArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (!IAuthToken.class.isAssignableFrom(parameter.getParameterType())) {
            return false;
        }
        AuthTokenCheck authTokenCheck = AnnotationUtil.findAnyAnnotation(parameter.getMethod(), AuthTokenCheck.class);
        return authTokenCheck != null && !authTokenCheck.disable();
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        return Objects.requireNonNull(webRequest.getNativeRequest(HttpServletRequest.class)).getAttribute(RequiredAuthTokenFilter.ATTRIBUTE_AUTH_TOKEN);
    }
}
